--[[
	prop_waterized - init.lua
		by Meoo~we
]]--
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include( 'shared.lua')

-- Accessor Funcs
function ENT:SetDamping( dmp )
    self.dt.damping = tonumber( dmp )
end

function ENT:SetDensity( den )
    self.dt.density = tonumber( den )
end

function ENT:SetBuoyancy( buo )
    self.Buoyancy = tonumber( buo )
end

function ENT:GetBuoyancy( )
    return self.Buoyancy
end

function ENT:SetPlayer( ply )
    self.Owner = ply
end

function ENT:GetPlayer( )
    return self.Owner
end

-- Serverside init
function ENT:Initialize()
    -- Basic stufff
    self:PhysicsInit( SOLID_VPHYSICS )
    self:SetMoveType( MOVETYPE_VPHYSICS )
    self:SetSolid( SOLID_VPHYSICS )
    -- Material & fix Z test
    self:SetMaterial( "waterizer/shader" )
    self:SetColor(255, 255, 255, 128)
    -- Nocollide
    self:SetCollisionGroup( COLLISION_GROUP_WORLD )
    self.CollisionGroup = COLLISION_GROUP_WORLD
    self:SetNotSolid(self:GetPlayer().w_EnableCollisions)
    -- Triggers
    self.Entity:SetTrigger( true )
end

-- Start touch hook
function ENT:StartTouch( ent )
    if not IsValid( ent )
    or not IsValid( ent:GetPhysicsObject() )
    or ent:GetClass() == "prop_waterized" then return end
    -- Create table if necessary
    ent.w_WaterEnts = ent.w_WaterEnts or {}
    table.insert(ent.w_WaterEnts, self)
    if not ent:IsPlayer() then
        table.insert(w_EntsInWater, ent)
        return
    end
    -- UMsg
    umsg.Start("w_StartTouch", ent)
        umsg.Entity( self )
    umsg.End()
end

-- End touch hook
function ENT:EndTouch( ent )
    if not IsValid( ent )
    or not IsValid( ent:GetPhysicsObject() )
    or ent:GetClass() == "prop_waterized" then return end
    if not ent.w_WaterEnts then return end
    -- Delete unused entities
    for k, e in ipairs(ent.w_WaterEnts) do
        if not IsValid(e) or e == self then
            table.remove(ent.w_WaterEnts, k)
        end
    end
    -- Set nil when table is useless
    if #(ent.w_WaterEnts) == 0 then
        ent.w_WaterEnts = nil
        if ent.w_IsInWater then
            ent:SetGravity(1)
            ent.w_IsInWater = false
        end
    end
    if not ent:IsPlayer() then
        for k, e in ipairs(w_EntsInWater) do
            if not IsValid(e) or e == self then
                table.remove(w_EntsInWater, k)
            end
        end
        return
    end
    -- UMsg
    umsg.Start("w_EndTouch", ent)
        umsg.Entity( self )
    umsg.End()
end
